<template>
  <div>
    <AForm :model="searchFrom" class="erp-search-form">
      <ARow class="grid-demo" :gutter="10">
        <ACol :span="6">
          <AFormItem hide-label content-class="">
            <AInput v-model="searchFrom.customerName" placeholder="客户名称" />
          </AFormItem>
        </ACol>
        <ACol :span="6">
          <AFormItem hide-label content-class="">
            <AInput v-model="searchFrom.productName" placeholder="产品名称" />
          </AFormItem>
        </ACol>
        <ACol :span="6">
          <AFormItem hide-label content-class="">
            <AInput v-model="searchFrom.sellersName" placeholder="业务员" />
          </AFormItem>
        </ACol>
        <ACol :span="6">
          <AFormItem hide-label content-class="">
            <ASelect v-model="searchFrom.orderStatus" allow-search placeholder="状态" allow-clear>
              <AOption label="已采购原材" value="已采购原材"></AOption>
              <AOption label="已生产" value="已生产"></AOption>
              <AOption label="已送货" value="已送货"></AOption>
            </ASelect>
          </AFormItem>
        </ACol>
      </ARow>
      <ARow class="erp-mt-10" :gutter="10">
        <ACol :span="6">
          <AFormItem hide-label content-class="">
            <ARangePicker
              v-model="searchFrom.planDeliveryDate"
              :placeholder="['计划交货日期', '计划交货日期']"
            />
          </AFormItem>
        </ACol>
        <ACol :span="6">
          <AFormItem hide-label content-class="">
            <ARangePicker
              v-model="searchFrom.createTime"
              :placeholder="['创建日期-开始', '创建日期-结束']"
            />
          </AFormItem>
        </ACol>
      </ARow>
    </AForm>
    <ACard :header-style="{ height: 'max-content' }">
      <div class="erp-mb-10 w100 erp-search-btn-box">
        <ASpace>
          <AButton type="primary" @click="onSearch">
            <template #icon>
              <icon-search />
            </template>
          </AButton>
          <ATooltip content="清空筛选项" position="top">
            <AButton type="dashed" @click="onReset">
              <template #icon>
                <icon-refresh />
              </template>
            </AButton>
          </ATooltip>
          <AButton v-if="isAuth([1, 2])" type="outline" @click="openEdit('新增')">新增</AButton>
          <ATooltip v-if="isAuth([1, 2])" :disabled="!isEmpty(selectRows)" content="请选择数据">
            <AButton
              type="outline"
              status="normal"
              :disabled="isEmpty(selectRows)"
              @click="fastGenerate('productMaterial')"
            >
              生成采购订单
            </AButton>
          </ATooltip>
          <ATooltip v-if="isAuth([1, 2])" :disabled="!isEmpty(selectRows)" content="请选择数据">
            <AButton
              type="outline"
              status="normal"
              :disabled="isEmpty(selectRows)"
              @click="fastGenerate('productionPlan')"
            >
              生成生产计划
            </AButton>
          </ATooltip>
          <ATooltip
            v-if="isAuth([1, 2])"
            :disabled="!(isEmpty(selectRows) || repeatCustomer)"
            content="请选择同一客户的数据"
          >
            <AButton
              type="outline"
              status="normal"
              :disabled="isEmpty(selectRows) || repeatCustomer"
              @click="fastGenerate('addDelivery')"
            >
              生成送货单
            </AButton>
          </ATooltip>
          <ATooltip v-if="isAuth([1, 2])" :disabled="!isEmpty(selectRows)" content="请选择产品">
            <AButton status="danger" :disabled="isEmpty(selectRows)" @click="batchDel()">
              批量删除
            </AButton>
          </ATooltip>
        </ASpace>
        <ASpace>
          <AButton type="primary" @click="onExport('table')">导出</AButton>
        </ASpace>
      </div>
      <ATable
        ref="tableRef"
        :pagination="false"
        :data="tableData"
        :bordered="{ cell: true }"
        :span-method="spanMethod"
        span-all
        column-resizable
        size="small"
        :row-selection="{
          type: 'checkbox',
          showCheckedAll: true
        }"
        row-key="saleOrderDetailId"
        @select="
          (rowKeys: (string | number)[], rowKey: string | number, record: TableData) =>
            tableEvent('select', { rowKeys, rowKey, record })
        "
        @select-all="(checked: boolean) => tableEvent('select-all', checked)"
      >
        <template #columns>
          <ATableColumn title="订单编号" data-index="saleOrderCode" :width="100"> </ATableColumn>
          <ATableColumn title="客户名称" data-index="customerName" :width="100"> </ATableColumn>
          <ATableColumn title="产品名称" data-index="productName" :width="150"> </ATableColumn>
          <ATableColumn title="规格型号" data-index="specModel" :width="100"> </ATableColumn>
          <ATableColumn title="数量" data-index="qty" :width="90" align="center"> </ATableColumn>
          <ATableColumn title="单价" data-index="unitPrice" :width="90" align="center">
          </ATableColumn>
          <ATableColumn title="金额" data-index="amt" :width="90" align="center">
            <template #cell="{ record }">
              {{ formatPrice(decimalRound(record.qty! * record.unitPrice!, 4)) }}
            </template>
          </ATableColumn>
          <ATableColumn title="状态" data-index="status" :width="100"> </ATableColumn>
          <ATableColumn title="总金额" data-index="totalAmt" :width="90" align="center">
            <template #cell="{ record }">
              {{ formatPrice(decimalRound(sumAmt(record), 4)) }}
            </template>
          </ATableColumn>
          <ATableColumn title="业务员" data-index="sellersName" :width="120"> </ATableColumn>
          <ATableColumn title="合同附件" data-index="fileList" :width="100" align="center">
            <template #cell="{ record }">
              <ADropdown trigger="hover">
                <ALink v-if="!isEmpty(record.fileList)">
                  {{ record.fileList.length }}
                </ALink>
                <template #content>
                  <ADoption
                    v-for="(flieInfo, index) in record.fileList"
                    :key="index"
                    @click="downloadFile(flieInfo.fileUrl)"
                  >
                    {{ flieInfo.fileName }}
                  </ADoption>
                </template>
              </ADropdown>
            </template>
          </ATableColumn>
          <ATableColumn title="计划交货日期" data-index="planDeliveryDate" :width="160">
            <template #cell="{ record }">
              <div v-if="record.planDeliveryDate">
                {{ dayjs(record.planDeliveryDate).format('YYYY-MM-DD') }}
              </div>
            </template>
          </ATableColumn>
          <ATableColumn title="含税" data-index="isInclTax" :width="70" align="center">
            <template #cell="{ record }">
              <icon-check-circle-fill v-if="record.isInclTax" style="color: #67c23a" size="20px" />
              <icon-close-circle-fill v-if="!record.isInclTax" style="color: red" size="20px" />
            </template>
          </ATableColumn>
          <ATableColumn title="送货方式" data-index="deliveryMethod" :width="90" align="center">
          </ATableColumn>
          <ATableColumn title="结算方式" data-index="settlementType" :width="90" align="center">
          </ATableColumn>
          <ATableColumn title="备注" data-index="remark" :width="100"> </ATableColumn>
          <ATableColumn title="创建人" data-index="createdBy" :width="120" align="center">
          </ATableColumn>
          <ATableColumn title="创建时间" data-index="createdDt" :width="120" align="center">
            <template #cell="{ record }">
              <div>{{ dayjs(record.createdDt).format('YYYY-MM-DD') }}</div>
            </template>
          </ATableColumn>
          <ATableColumn title="更新时间" data-index="remark" :width="120" align="center">
            <template #cell="{ record }">
              <div>{{ dayjs(record.updatedDt).format('YYYY-MM-DD') }}</div>
            </template>
          </ATableColumn>
          <ATableColumn v-if="isAuth([1, 2])" title="操作" :width="145" fixed="right">
            <template #cell="{ record }">
              <ASpace>
                <AButton type="primary" size="mini" @click="rowEvent(record, 'edit')">
                  修改
                </AButton>
                <AButton type="primary" size="mini" @click="rowEvent(record, 'print')">
                  打印
                </AButton>
              </ASpace>
              <ASpace class="erp-mt-6">
                <AButton type="primary" size="mini" @click="rowEvent(record, 'copy')">
                  复制
                </AButton>
                <AButton status="danger" size="mini" @click="rowEvent(record, 'del')">
                  删除
                </AButton>
              </ASpace>
            </template>
          </ATableColumn>
        </template>
      </ATable>
      <div class="arco-table-pagination">
        <APagination
          :total="pageParam.totalCount"
          :page-size="pageParam.pageSize"
          show-total
          @change="(page: number) => tableEvent('page-change', page)"
        />
      </div>
    </ACard>
    <EditPopupForm
      v-model:visible="editModal"
      :title="editModalTitle"
      :check-data="rowData"
      @reload="
        () => {
          getTableData()
          clearTableSelect()
        }
      "
    >
    </EditPopupForm>
    <salesBillPrint v-if="detailData" ref="salesPrintRef" :check-data="detailData"></salesBillPrint>
    <batchAddProductionPlan
      v-model:visible="fastGenerateModal.productionPlan"
      title="新增生产计划"
      :check-data="selectRows"
      @reload="
        () => {
          getTableData()
          clearTableSelect()
        }
      "
    >
    </batchAddProductionPlan>
    <addPurchaseFinished
      v-model:visible="fastGenerateModal.productMaterial"
      title="新增采购单"
      :check-data="{ detailList: purchaseList }"
      from-module="product"
      @reload="
        () => {
          getTableData()
          clearTableSelect()
        }
      "
    ></addPurchaseFinished>
    <batchAddDelivery
      v-model:visible="fastGenerateModal.addDelivery"
      title="新增送货单"
      :check-data="selectRows"
      @reload="
        () => {
          getTableData()
          clearTableSelect()
        }
      "
    ></batchAddDelivery>
  </div>
</template>

<script lang="ts" setup>
import EditPopupForm from './editPopupForm.vue'
import salesBillPrint from './print.vue'
import batchAddProductionPlan from './batchAddProductionPlan.vue'
import batchAddDelivery from './batchAddDelivery.vue'
import dayjs from 'dayjs'
import { Message, Modal, TableData } from '@arco-design/web-vue'
import { isAuth } from '@renderer/utils/auth'
import { decimalRound, formatPrice } from '@renderer/utils/mixins'
import {
  batchDelSale,
  delSale,
  getSaleAllList,
  getSaleDetail,
  getSalePageList,
  SaleResItem,
  SaleResItemHandle,
  SaleSearch
} from '@renderer/api/salesDep'
import { cloneDeep, isEmpty, sum, sumBy, uniqBy } from 'lodash-es'
import addPurchaseFinished from '@renderer/views/purchasingDepartment/purchaseFinished/editPopupForm.vue'
import { PurchaseReq } from '@renderer/api/purchasingDep'
import { downloadFile } from '@renderer/utils/mixins'

const searchFrom = ref<SaleSearch>({})
const editModal = ref(false)
const editModalTitle = ref('新增')
const tableData = ref<SaleResItemHandle[]>([])
const pageParam = reactive({
  currentPage: 1,
  pageSize: 20,
  totalCount: 0
})
const salesPrintRef = ref<InstanceType<typeof salesBillPrint>>() // 打印组件
const detailData = ref<SaleResItem>()
const fastGenerateModal = ref({
  productionPlan: false,
  productMaterial: false,
  addDelivery: false
})
const productMaterialList = ref<PurchaseReq['detailList']>([])
const selectRows = ref<SaleResItemHandle[]>([])
const tableRef = ref()
const purchaseList = ref([]) // 采购数据
const repeatCustomer = computed(() => uniqBy(selectRows.value, 'customerName').length > 1)

onMounted(() => {
  getTableData()
})

function clearTableSelect() {
  tableRef.value?.selectAll(false)
  selectRows.value = []
}

function sumAmt(rowData: SaleResItem) {
  const amts = rowData.detailList.map((item) =>
    Number(decimalRound(item.qty! * item.unitPrice!, 4))
  )
  return sum(amts)
}

function batchDel() {
  const idList = selectRows.value.map((item) => item.saleOrderId)
  batchDelSale({ idList: idList }).then(() => {
    Message.success('删除成功')
    onSearch()
    clearTableSelect()
  })
}

function formatData(baseData: SaleResItem[]): SaleResItemHandle[] {
  return baseData
    .map((item, index) => {
      item.index = index + 1
      if (!isEmpty(item.detailList)) {
        return item.detailList.map((detailItem, index) => {
          if (index === 0) {
            return {
              ...detailItem,
              ...item,
              span: item.detailList.length,
              totalAmt: sumBy(item.detailList, 'amt')
            }
          } else {
            return { ...detailItem, ...item }
          }
        })
      } else {
        return [item] as SaleResItemHandle[]
      }
    })
    .flat()
}
async function getTableData() {
  const [createdStartDate, createdEndDate] = searchFrom.value.createTime! || []
  searchFrom.value.createdStartDate = createdStartDate
    ? dayjs(createdStartDate).format('YYYY-MM-DD')
    : ''
  searchFrom.value.createdEndDate = createdEndDate ? dayjs(createdEndDate).format('YYYY-MM-DD') : ''

  const [planDeliveryStartDate, planDeliveryEndDate] = searchFrom.value.planDeliveryDate! || []
  searchFrom.value.planDeliveryStartDate = planDeliveryStartDate
    ? dayjs(planDeliveryStartDate).format('YYYY-MM-DD')
    : ''
  searchFrom.value.planDeliveryEndDate = planDeliveryEndDate
    ? dayjs(planDeliveryEndDate).format('YYYY-MM-DD')
    : ''
  const res = await getSalePageList({ ...searchFrom.value, ...pageParam })
  tableData.value = formatData(res.data.list)
  pageParam.totalCount = res.data.totalCount!
}

const onSearch = () => {
  pageParam.currentPage = 1
  getTableData()
}
function onReset() {
  searchFrom.value = {}
  pageParam.currentPage = 1
  pageParam.pageSize = 20
  getTableData()
  clearTableSelect()
}

function tableEvent(type: 'page-change' | 'select' | 'select-all', param: any) {
  switch (type) {
    case 'page-change':
      pageParam.currentPage = param
      getTableData()
      break
    case 'select':
      {
        const { rowKeys, rowKey, record } = param
        if (rowKeys.includes(rowKey)) {
          selectRows.value.push(record)
          // 判断是否全选
          const tempIDs = selectRows.value.map((item) => item.saleOrderId)
          if (tableData.value.every((item) => tempIDs.includes(item.saleOrderId))) {
            tableRef.value.selectAll(true)
          }
        } else {
          selectRows.value = selectRows.value.filter(
            (item) => item.saleOrderId != record.saleOrderId
          )
        }
        // console.log(selectRows.value)
      }
      break
    case 'select-all':
      if (param) {
        selectRows.value = selectRows.value.concat(tableData.value)
        selectRows.value = uniqBy(selectRows.value, 'saleOrderId')
      } else {
        const ids = tableData.value.map((item) => item.saleOrderId)
        selectRows.value = selectRows.value.filter((item) => !ids.includes(item.saleOrderId!))
      }
      break
    default:
      break
  }
}
const spanMethod = ({ record, columnIndex }) => {
  if (columnIndex < 3 || columnIndex > 8) {
    if (record.span) {
      return {
        colspan: 1,
        rowspan: record.span
      }
    }
  }
}

function openEdit(title: string) {
  rowData.value = {}
  editModalTitle.value = title
  editModal.value = true
}

const rowData = ref({})
function rowEvent(row: SaleResItem, type: 'del' | 'copy' | 'edit' | 'print') {
  switch (type) {
    case 'del':
      Modal.warning({
        title: '警告',
        content: '当前数据删除后不可恢复，是否继续？',
        okText: '确认',
        cancelText: '取消',
        simple: false,
        hideCancel: false,
        maskClosable: false,
        closable: false,
        onOk: () => {
          delSale({ saleOrderId: row.saleOrderId! }).then(() => {
            Message.success('删除成功')
            getTableData()
          })
        },
        onCancel: () => {}
      })
      break
    case 'copy':
      rowData.value = row
      editModalTitle.value = '复制'
      editModal.value = true
      break
    case 'edit':
      rowData.value = row
      editModalTitle.value = '修改'
      editModal.value = true
      break
    case 'print':
      rowData.value = row
      getSaleDetail({ saleOrderId: row.saleOrderId }).then((res) => {
        detailData.value = res.data
        nextTick(() => salesPrintRef.value?.printInfo())
      })
      break

    default:
      break
  }
}

function fastGenerate(type: keyof typeof fastGenerateModal.value) {
  fastGenerateModal.value[type] = true
  productMaterialList.value = selectRows.value.flatMap((item) => item.detailList)
  // 组装采购单数据
  const temp = {}
  for (const element of productMaterialList.value) {
    if (!temp[element.productId!]) {
      temp[element.productId!] = cloneDeep(element)
    } else {
      temp[element.productId!].qty += element.qty
    }
  }
  purchaseList.value = Object.values(temp)
}

async function onExport(type: 'table' | 'template') {
  let fileTitle: string
  const headerData = [
    { title: '订单编号', value: 'saleOrderCode', width: 180 },
    { title: '客户名称', value: 'customerName', width: 180 },
    { title: '产品名称', value: 'productName', width: 180 },
    { title: '规格型号', value: 'specModel', width: 100 },
    { title: '数量', value: 'qty', width: 100 },
    { title: '单价', value: 'unitPrice', width: 100 },
    { title: '金额', value: 'amt' },
    { title: '业务员', value: 'sellersName' },
    { title: '状态', value: 'orderStatus' },
    { title: '合同附件', value: 'files' },
    { title: '计划交货日期', value: 'planDeliveryDate' },
    { title: '含税', value: 'isInclTax' },
    { title: '送货方式', value: 'deliveryMethod' },
    { title: '结算方式', value: 'settlementType' },
    { title: '备注', value: 'remark' }
  ]
  let excelData: SaleResItemHandle[] = []
  switch (type) {
    case 'table':
      {
        fileTitle = '销售订单数据'
        headerData.unshift({ title: '序号', value: 'index', width: 80 })
        const res = await getSaleAllList(searchFrom.value)
        excelData = formatData(res.data.list)
        excelData = excelData.map((item) => {
          item.isInclTax = item.isInclTax ? '是' : '否'
          item.files = item.fileList?.map((item) => item.fileUrl)
          return item
        })
      }
      break
    default:
      break
  }
  import('@renderer/utils/vendor').then((excel) => {
    excel.exportExcel(excelData, headerData, fileTitle)
  })
}
</script>
<style lang="less" scoped>
.erp-search-btn-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
